#!/bin/bash
# get kubernetes container info

if [[ $1 == '--help' ]];then
    echo; echo "Usage: $0 <pod_keywords> <namespace>"; echo;
    exit 1
fi

KEYWORDS=${1:-all}

NAMESPACE=${2:-__NAMESPACE}

KUBESERVER=__KUBE_MASTER


if [[ ${KEYWORDS} == "all" ]];then
	PODS=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -v 'NAME' | cut -d' ' -f1)
	PODSNUM=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -v 'NAME' | cut -d' ' -f1 | wc -l)
else
	PODS=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -i ${KEYWORDS} | cut -d' ' -f1)
	PODSNUM=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -i ${KEYWORDS} | cut -d' ' -f1 | wc -l)
fi


PS3='Choose to get info options(input "q" to exit)> '

select pod in ${PODS};do

    if [[ "$REPLY" =~ ^[0-9]+$ ]] && [ "$REPLY" -ge 1 -a "$REPLY" -le $PODSNUM ];then
        echo -en "##########\\033[1;31m BEGIN \\033[0;39m##########";echo;echo
		# get container ip
		cip=$(kubectl --server=${KUBESERVER} describe pods $pod --namespace=${NAMESPACE} | grep IP: | cut -d':' -f2 | xargs -n1)
		# get containter id
		cid=$(kubectl --server=${KUBESERVER} describe pods $pod --namespace=${NAMESPACE} | grep 'Container ID:' | cut -d'/' -f3)
		# get node ip address that cid
		nip=$(kubectl --server=${KUBESERVER} describe pods $pod --namespace=${NAMESPACE} | grep 'Node:' | cut -d'/' -f2)
	
		echo "Container ID:      "${cid:0:12}
		echo "Container IP:      "$cip
		echo "Container Node IP: "$nip

    elif [ "$REPLY" == 'q' ];then
        break
    else
        echo -en "##########\\033[1;31m BEGIN \\033[0;39m##########";echo
        echo 'Input error'
    fi

    REPLY=''
    echo;echo -en "##########\\033[1;31m  END  \\033[0;39m##########";echo
done
